using System;
using System.Linq.Expressions;
using System.Reflection;

namespace AbstractClass.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public static class ReflectionExtensions
    {
        /// <summary>
        /// Calls the method.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="methodInfo">The method info.</param>
        /// <returns></returns>
        public static Action<object, T> CallMethod<T>(this MethodInfo methodInfo)
        {
            if (!methodInfo.IsPublic) return null;

            ParameterExpression returnParameter = Expression.Parameter(typeof(object), "method");
            ParameterExpression valueArgument = Expression.Parameter(typeof(T), "argument");

            MethodCallExpression setterCall = Expression.Call(
                                            Expression.ConvertChecked(returnParameter, methodInfo.DeclaringType),
                                            methodInfo,
                                            Expression.Convert(valueArgument, typeof(T)));
            return Expression.Lambda<Action<object, T>>(setterCall, returnParameter, valueArgument).Compile();
        }
    }
}